<?php
namespace Home\Controller;

use Think\Controller;
use Common\Util\BankCard;
use Common\Util\LanzSMSDirectSendSMS;
use Think\Page;

class BeauticianController extends Controller {
	
	const MAX_LOAD_LIMIT = 5;
	
	public function _initialize() {
		$pathParams = I('path.');
		$action = isset($pathParams [1])?$pathParams [1]:false;
		$this->assign('select', $action);
		if (!isset($_SESSION ['beautician'])) {
			$hash = isset($_COOKIE ['hash'])?$_COOKIE ['hash']:'';
			if ($hash) {
				$RememberModel = D('RememberLogin');
				$record = $RememberModel->getRememberRecord($hash);
				
				if ($record) {
					$BeauticianModel = D ( 'Beautician' );
					$beautician = $BeauticianModel->getBeauticianInfo($record ['beautician_id']);
					//弃用已使用的hash，一个hash只能使用一次
					$RememberModel->discardRecord($hash);
					if ($hash == md5($beautician ['id'] .'-'. $beautician ['password'].$record ['created'])) {
						$_SESSION ['beautician'] == serialize($beautician);
							
						$created = time();
						$newHash = md5($beautician ['id'] .'-'. $beautician ['password'].$created);
						$record = array(
							'hash' => $newHash,
							'beautician_id' => $beautician ['id'],
							'created' => $created
						);
						$RememberModel->add($record);
						setcookie('hash', $newHash, $created + 7 * 24 * 3600);
					}
				}
			}
		}
		
		if ($action != 'sendCode' && 
			$action != 'confirmResetPassword' && 
			$action != 'login' && 
			$action != 'repeat') {
			if (!isset($_SESSION ['beautician'])) {
				redirect('login');
			}
		} else {
			if ($action == 'login' && $_SESSION ['beautician']) {
				redirect('beauticianOrder');
			}
		}
		
		if (C('JS_DEBUG')) {
			$this->assign('JSDEBUG', '?t='.time());
		}
	}

	private $orderType = array('complete' => 4, 'cancel' => 7, 'not_use' => 1);
	
	
	/**
	 * 添加银行卡
	 */
	public function addCard() {
		if (IS_POST) {
			$cardModel = D ( 'Card' );
			$cardHolder = I ( 'post.cardHolder' );
			$card = I ( 'post.card' );
			
			$target_id = getBeauticianId();
			$where = array('target_id' => $target_id, 'card' => $card);
			$cardBindRecord = $cardModel->where($where)->find();
			if (!$cardBindRecord) {
				$BankCard = new BankCard ();
				$cardInfo = $BankCard->query ( $card );
				if (!$cardInfo) {
					$this->ajaxReturn(array('status' => 0, 'message' => '获取银行卡信息失败'));
				}
				
				$last_four_number = substr ( $card, -4 );
				$bank_name = $cardInfo ['bank_name'];
				$card_type = $cardInfo ['card_type'];
				$data = array (
					'cardHolder' => $cardHolder,
					'card' => $card,
					'bank_name' => $bank_name,
					'card_type' => $card_type,
					'target_id' => $target_id,
					'last_four_number' => $last_four_number,
					'status'	=> 1,
					'created' => time()
				);
				if ($cardModel->add ( $data )) {
					$this->ajaxReturn(array('status' => 1, 'redirect' => U ( 'bank_list' )));
				} else {
					$this->ajaxReturn(array('status' => 0, 'message' => '获取银行卡信息失败'));
				}
			} else {
				if ($cardBindRecord ['status'] == 1) {
					$this->ajaxReturn(array('status' => 0, 'message' => '改银行卡已绑定，请选择其它银行卡'));
				} else {
					$result = $cardModel->where($where)->save(array('status' => 1));
					if ($result) {
						$this->ajaxReturn(array('status' => 1, 'redirect' => U ( 'bank_list' )));
					} else {
						$this->ajaxReturn(array('status' => 0, 'message' => '获取银行卡信息失败'));
					}
				}
			}
		} else {
			$this->assign('beautician', getBeautician());
			$this->display ();
		}
	}
	
	/**
	 * 查询邦定的银行卡
	 */
	public function bank_list() {
		$cardModel = D ( 'Card' );
		$id = getBeauticianId();
		
		$lists = $cardModel->field(array('c.*', 'b.icon'))
			->join('c left join mdd_bank as b on c.bank_name=b.bank_name')
			->where(array('target_id' => $id))->select ();
	
		$this->assign('bankList', $lists);
		$this->display ();
	}
	
	/**
	 * 订单列表
	 */
	public function beauticianOrder() {
		$beauticianId = getBeauticianId();
		$OrderModel = D('Order');
		$type = I ('get.type');
		if ($type) {
			$status = $this->orderType [$type];
			$OrderModel->order = 'order_time DESC';
		} else {
			$status = 1;
		}
	
		$OrderModel->status = $status;
		$count = $OrderModel->totalBeauticianOrder($beauticianId);
		$Page = new Page($count);
		$OrderModel->offset = $Page->firstRow;
		$OrderModel->limit = $Page->listRows;
		
		$BeauticianModel = D('Beautician');
		$beauticianInfo = getBeautician();
	
		$BeautyParlor = D('BeautyParlor');
		if (!IS_AJAX) {
			$totalOrder = D('Order')->where(array('beautician_id' => $beauticianId, 'status=1 or status=3'))->count();
			$totalCompleteOrder = D('Order')->where(array('beautician_id' => $beauticianId, 'status' => 4))->count();
			$cancelOrder = D('Order')->where(array('beautician_id' => $beauticianId, 'status' => 7))->count();

			$this->assign('total', $totalOrder);
			$this->assign('totalCompleteOrder', $totalCompleteOrder);
			$this->assign('cancelOrder', $cancelOrder);
			
			$this->assign('serviceTotal', $totalOrder + $totalCompleteOrder);
			$this->assign('beauty', $BeautyParlor->getBestBeautyOfBeautician($beauticianId));
			$this->assign('beautician', $beauticianInfo);
			$start = floor(($beauticianInfo ['professional_score'] + $beauticianInfo ['punctuality_score'] + $beauticianInfo ['communication_score'])/(3 * $beauticianInfo ['comment_total']));
				
			$this->assign('start', round($start, 1));
			$this->display();
		} else {
			$timer = 0;
			$currentService = false;
			
			if ($type == '') {
				if (!isset($_SESSION ['current_service']) || !$_SESSION ['current_service']) {
					$orderInfo = $OrderModel->getBeauticianCurrentService($beauticianId);
					
					if ($orderInfo) {
						$currentService = array('start_service_time' => $orderInfo ['use_time'],
							'end_service_time' => $orderInfo ['use_time'] + $orderInfo ['service_time'] * 60,
							'order_id' => $orderInfo ['id']
						);
						$_SESSION ['current_service'] = serialize($currentService);
						$timer = $orderInfo ['use_time'] +$orderInfo ['service_time'] * 60 - time();
					}
// 					 else {
// 						unset($_SESSION ['current_service']);
// 					}
				}
// 				 else {
// 					$currentService = unserialize($_SESSION ['current_service']);
// 					if (!($currentService && $currentService ['end_service_time'] > time())) {
// 						unset($_SESSION ['current_service']);
// 						$currentService = false;
// 					} else {
// 						$timer = $currentService ['end_service_time'] - time();
// 					}
// 				}
			}
			
			$orderIds = $OrderModel->getBeauticianOrders($beauticianId);
			$list = array();
			
			if ($orderIds) {
				$UserModel = D('User');
				foreach ($orderIds as $key => $value) {
					$orderInfo = $OrderModel->getOrderInfo($value ['id']);
					$list [$key] = $orderInfo;
					$userInfo = $UserModel->getUserById($orderInfo ['user_id']);
					$list [$key] ['user_info'] = $userInfo;
					$list [$key] ['beauty'] = $BeautyParlor->getBeautyInfo($orderInfo ['beauty_id']);
// 					$OrderModel->clearCache($value ['id']);
					if ($orderInfo ['status'] == 3 && 
						(($orderInfo ['order_time'] + $orderInfo ['service_time'] * 60) < $orderInfo ['use_time']
							|| ($orderInfo ['use_time'] + $orderInfo ['service_time'] * 60) < time())) {
						$list [$key] ['check_complete'] = true;
					}
				}
			}
			
			$this->assign('list', $list);
			foreach ($list as $key => &$value) {
				$value ['format_time'] = date('Y-m-d H:i', $value ['order_time']);
			}
			$ajaxReturnData = array('status' => 1, 'data' => $list);
			if ($currentService) {
				$ajaxReturnData ['timer'] = $timer * 1000;
				$ajaxReturnData ['current'] = $currentService;
			}
			$this->ajaxReturn($ajaxReturnData);
		}
	}
	
	/**
	 * 订单完成
	 */
	public function completeUse() {
		$orderId = I('get.id');
	
		$OrderModel = D('Order');
		$orderInfo = $OrderModel->getOrderInfo($orderId);
		$beauticianId = getBeauticianId();
		if ($orderInfo ['beautician_id'] != $beauticianId) {
			$this->ajaxReturn(array('status' => 0, 'message' => '服务结束失败'));
		}
		
		if (($orderInfo ['use_time'] + $orderInfo ['service_time'] * 60) > time() &&
			$orderInfo ['order_time'] + $orderInfo ['service_time'] * 60 > $orderInfo ['use_time']) {
			$this->ajaxReturn(array('status' => 0, 'message' => '服务未完成，不能结束服务'));
		}
		 
		$beautician = getBeautician();
	
		switch ($orderInfo ['status']) {
			case 0:
				$this->ajaxReturn(array('status' => 0, 'message' => '订单已删除'));
				break;
			case 2:
				$this->ajaxReturn(array('status' => 0, 'message' => '订单未支付'));
				break;
			case 4:
				$this->ajaxReturn(array('status' => 0, 'message' => '订单已使用'));
				break;
			case 5:
				$this->ajaxReturn(array('status' => 0, 'message' => '订单已取消'));
				break;
		}
	
		$result = $OrderModel->where(array('id' => $orderId))->save(array('status' => 4, 'use_end_time' => time()));
		if ($result) {
			$BeauticianModel = D('Beautician');
	    	$BeauticianModel->where(array('id' => $orderInfo ['beautician_id']))->setInc('service_total', 1);
	    	$BeauticianModel->clearCache($orderInfo ['beautician_id']);
	    	
	    	$ServiceItemModel = D('ServiceItem');
	    	$BeautyModel = D('BeautyParlor');
	    	
	    	//美容师服务次数，完成服务后计算
	    	$BeautyModel->where(array('id' => $one ['beauty_id']))->setInc('service_total',1);
	    	$BeautyModel->clearCache($one ['beauty_id']);
	    	$ServiceItemModel->where(array('id' => $one ['service_id']))->setInc('purchases_total',1);
	    	$ServiceItemModel->clearCache($one ['service_id']);
	    	
			unset($_SESSION ['current_service']);
			$OrderModel->clearCache($orderId);
			\Think\Hook::listen('complete_service', $orderInfo);
	
			$this->ajaxReturn(array('status' => 1));
		} else {
			$this->ajaxReturn(array('status' => 0, 'message' => '完成服务设置失败！'));
		}
	}
	
	/**
	 * 服务统计金额
	 */
	public function count() {
		$beauModel = D ( 'Beautician' );
		$id = getBeauticianId();
	
		$where = array('id' => $id);
		$amount = $beauModel->field ( 'serviceAmount' )->where ($where)->find ();
		if ($amount && $amount ['serviceAmount']) {
			$this->assign ( 'amount', $amount ['serviceAmount']);
		}
	
		$setting = getGlobleConfig();
		$this->assign('count_cash_day', $setting['count_cash_day']);
		$this->assign('beautician', $beauticianInfo);
		$this->display ();
	}
	
	/**
	 * 提现
	 */
	public function count_cash() {
		if (IS_POST) {
			$recordModel = D ( 'PresentRecord' );
			$BeauticianModel = D ( 'Beautician' );
			$cardholder = I ( 'post.cardholder' );
			$money = I ( 'post.money' );
			$remark = I ( 'post.remark' );
			$card_id = I ( 'post.card_id' );
			$created = time ();
			$id = getBeauticianId();
			//$id=$beautician['id'];
				
			// 提现修改金额的变动
			$dataBeau = $BeauticianModel->field ( 'serviceAmount' )->where ( "id='$id'" )->find ();
			$serviceAmount = $dataBeau ['serviceAmount'];
				
			$serviceAmount = $serviceAmount - $money;
			if ($serviceAmount < 0) {
				$this->error('提现金额大于收益金额');
				exit;
			}
				
			$data = array (
					'cardholder' => $cardholder,
					'money' => $money,
					'remark' => $remark,
					'beautician_id' => $id,
					'card_id' => $card_id,
					'created' => $created
			);
				
			$recordModel->startTrans();
			$result = $recordModel->add($data);
			if ($result) {
				$inComeModel = D('IncomeStatement');
				$incomeResult = $inComeModel->expend($data ['beautician_id'], $data ['money'], $data ['remark']);
				if (!$incomeResult) {
					$recordModel->rollback();
					$this->error('提现失败,添加明细失败');
					exit;
				}
	
				$Beautician = D('Beautician');
				$where = array('id' => $id);
				$updateBeauticianResult = $Beautician->where ($where)
				->save (array('serviceAmount' => $serviceAmount));
				if (!$updateBeauticianResult) {
					$recordModel->rollback();
					$this->error('提现失败,更新美容师信息失败');
					exit;
				}
	
				$recordModel->commit();
				$this->success ( '提现成功', U ( 'cash_list' ) );
			} else {
				$this->error ( '提现失败' );
			}
		} else {
				
			$weekDay = date('w', time());
			$setting = getGlobleConfig();
			if ($weekDay != $setting['count_cash_day']) {
				$this->error('还没有到提现的日期');
				exit;
			}
				
			$CardModel = D ( 'Card' );
			$id = getBeauticianId();
			$cardList = $CardModel->getBeauticianCard($id);
				
			$BeauticianModel = D ( 'Beautician' );
			$amount = $BeauticianModel->field ( 'serviceAmount' )->where ( "id='$id'" )->find ();
			$this->assign ( 'data', $cardList );
				
			if ($amount && $amount ['serviceAmount']) {
				$this->assign ( 'amount', $amount ['serviceAmount']);
			}
				
			$this->display ();
		}
	}
	
	/**
	 * 收支明细
	 */
	public function cash_list() {
		$id = getBeauticianId();
		$incomeModel = D('IncomeStatement');
	
		$count = $incomeModel->beauticianIncomeTotal($id);
		$page = new Page($count, 8);
	
		$list = $incomeModel->getBeauticanIncome($id, $page->firstRow, $page->listRows);
	
		$nowPage = I('get.p')?I('get.p'):1;
	
		$hasMore = $nowPage * 8 < $count;
		$nextPage = U('/Beautician/cash_list/p/'.($nowPage + 1));
		
		if (!IS_AJAX) {
			if ($hasMore) {
				$this->assign('nextPage', $nextPage);
			}
			
			$this->assign('hasMore', $hasMore);
			$this->assign('beautician', getBeautician());
			$this->assign('data', $list);
			$this->display();
		} else {
			$list = array_map(function ($var) {
				$var ['time'] = date('Y-m-d H:i:s', $var ['created']);
				return $var;
			}, $list);
			
			$data = array(
				'status' => 1,
				'hasMore' => $hasMore,
				'nextPage' => $hasMore?$nextPage:false,
				'data' => $list
			);
			
			$this->ajaxReturn($data);
		}
	}
	
	public function sql() {
		$M = M();
		
// 		$OrderModel = D('Order');
// 		$BeauticianModel = D('Beautician');
		
// 		$list = $BeauticianModel->select();
// 		foreach ($list as $value) {
// 			$total = $OrderModel->where(array('beautician_id' => $value ['id'], 'status' => 4))->count();
// 			$BeauticianModel->where(array('id' => $value ['id']))->save(array('service_total' => $total));
// 			$BeauticianModel->clearCache($value ['id']);
// 		}
		
// 		M('message_notice_record')->where(array('id' => 1))->save(array('type' => 'verification'));
// 		dump($M->query("CREATE TABLE IF NOT EXISTS `mdd_order_change` (
//   `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
//   `order_id` int(10) unsigned NOT NULL COMMENT '订单编号',
//   `old_order_time` int(11) unsigned NOT NULL COMMENT '预约时间',
//   `new_order_time` int(11) unsigned NOT NULL COMMENT '改签时间',
//   `status` tinyint(1) NOT NULL DEFAULT '1',
//   `created` int(11) unsigned NOT NULL,
//   PRIMARY KEY (`id`)
// ) ENGINE=InnoDB  DEFAULT CHARSET=latin1 COMMENT='订单改签记录' AUTO_INCREMENT=1 ;"));

// 		M('message_notice_record')->where(array('id' => 1))->save(array('type' => 'verification'));
// 		dump($M->query("CREATE TABLE IF NOT EXISTS `mdd_refund_record` (
//   `id` int(10) NOT NULL AUTO_INCREMENT,
//   `order_id` int(10) NOT NULL,
//   `card_id` int(10) NOT NULL COMMENT '银行卡编号',
//   `bank_full_name` varchar(45) DEFAULT '0' COMMENT '开户行',
//   `remark` varchar(255) NOT NULL DEFAULT '0' COMMENT '备注',
//   `status` tinyint(1) NOT NULL DEFAULT '0' COMMENT '0正在处理 1已转账',
//   `created` int(11) NOT NULL,
//   PRIMARY KEY (`id`)
// ) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COMMENT='退款记录表' AUTO_INCREMENT=1 ;"));

// 		dump($M->query("CREATE TABLE IF NOT EXISTS `mdd_message_notice_record` (
//   `id` int(10) NOT NULL AUTO_INCREMENT,
//   `type` enum('before','verification','pay_success','notpay') NOT NULL COMMENT '短信类型',
//   `target_id` int(10) NOT NULL DEFAULT '0' COMMENT '短信接受者',
//   `order_id` int(10) NOT NULL DEFAULT '0' COMMENT '发送订单类短信必须',
//   `mobile` varchar(15) NOT NULL COMMENT '接受手机号',
//   `status` tinyint(1) NOT NULL DEFAULT '0' COMMENT '发送成功状态 1成功 0失败',
//   `created` int(11) NOT NULL DEFAULT '0',
//   PRIMARY KEY (`id`)
// ) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COMMENT='短信发送记录表' AUTO_INCREMENT=1 ;"));

// 		dump($M->query("CREATE TABLE IF NOT EXISTS `mdd_user_weixin_relationship` (
//   `id` int(10) NOT NULL AUTO_INCREMENT,
//   `user_id` int(10) NOT NULL COMMENT '用户编号',
//   `open_id` varchar(40) NOT NULL COMMENT '微信Openid',
//   `status` tinyint(1) NOT NULL DEFAULT '1',
//   `created` int(11) NOT NULL COMMENT '绑定时间',
//   PRIMARY KEY (`id`)
// ) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COMMENT='用户微信账号绑定表' AUTO_INCREMENT=1 ;"));

// 		dump($M->query("CREATE TABLE IF NOT EXISTS `mdd_bank` (
//   `id` int(3) NOT NULL AUTO_INCREMENT,
//   `bank_name` varchar(40) NOT NULL COMMENT '银行类型',
//   `icon` varchar(40) NOT NULL COMMENT '银行图标',
//   `update_time` int(11) NOT NULL DEFAULT '0' COMMENT '更新时间',
//   `create_time` int(11) NOT NULL DEFAULT '0' COMMENT '创建时间',
//   PRIMARY KEY (`id`)
// ) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COMMENT='银行类型管理' AUTO_INCREMENT=8 ;"));
// 				dump(M()->query('SHOW FULL COLUMNS FROM mdd_bank'));die;

// 		dump($M->query("update mdd_order set iscomment=1 where id in (select post_id from mdd_comments where parentid=0)"));

// 		$orders = M('order')->where(array('status' => '4'))->select();
// 		foreach ($order as $order) {
// 			dump(S('Order_'.$order ['id']));
// 		}
		
// 		dump($M->query("ALTER TABLE  `mdd_user_coupon` ADD  `expiry_type` TINYINT( 1 ) NOT NULL COMMENT  '过期类型' AFTER  `use_time`;"));
// 		dump($M->query("update mdd_user_coupon set `expiry_type`=(select expiry_type from mdd_coupon_code where c_id=coupon_id);"));

// 		dump($M->query("ALTER TABLE  `mdd_user` CHANGE  `select_province` `select_province` VARCHAR( 40 ) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT  '0' COMMENT  '选择省份'"));
// 		dump($M->query("ALTER TABLE  `mdd_user` CHANGE  `select_city`  `select_city` VARCHAR( 40 ) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT  '0' COMMENT  '所在城市'"));
		// dump(M()->query("ALTER TABLE  `".C('DB_PREFIX')."_config` ADD  `beautician_commission` FLOAT( 4, 2 ) NOT NULL DEFAULT  '0' COMMENT  '美容师提成率 0-1' AFTER  `max_search_size`"));
		// $arrayName = array('beautician_commission' => 0.90, );
		// S('GLOBLE_SETTING', null);
		// dump(M()->query('SHOW FULL COLUMNS FROM '.C('DB_PREFIX').'_config'));die;
	}
	
	/**
	 * 获取美容师的工作时间
	 */
	public function getTime() {
		$todayDate = date ( 'Y-m-d' );
		$dayStart = strtotime ( $todayDate . ' 00:00:00' );
		$dayEnd = strtotime ( $todayDate . ' 23:59:59' );
		$todayStart = strtotime ( $todayDate . ' 08:00:00' );
		$todayEnd = strtotime ( $todayDate . ' 22:00:00' );
	
		$id = getBeauticianId();
		$ScheduleModel = M('schedule');
		$setting = $ScheduleModel->where(array('uid' => $id))->order('CurrentDate DESC')->limit(1)->find();
		if ($setting) {
			$setting = unserialize($setting ['workTime']);
		}
		
		if (!$setting) {
			$todaySetting = 0;
			$tomorrowSetting = 0;
			$afterTomorrowSetting = 0;
		} else {
			if (array_key_exists($dayStart, $setting)) {
				$todaySetting = $setting [$dayStart];
				if ($todaySetting == 0) {
					$todaySetting = array();
				}
			} else {
				$todaySetting = 0;
			}
			
			if (array_key_exists(strtotime ( '+1 day', $dayStart), $setting)) {
				$tomorrowSetting = $setting [strtotime ( '+1 day', $dayStart)];
				if ($tomorrowSetting == 0) {
					$tomorrowSetting = array();
				}
			} else {
				$tomorrowSetting = 0;
			}
			
			if (array_key_exists(strtotime ( '+2 day', $dayStart), $setting)) {
				$afterTomorrowSetting = $setting [strtotime ( '+2 day', $dayStart)];
				if ($afterTomorrowSetting == 0) {
					$afterTomorrowSetting = array();
				}
			} else {
				$afterTomorrowSetting = 0;
			}
		}
		
	
		$data = array (
			'today' => array (
				'day_start' => $dayStart,
				'day_end' => $dayEnd,
				'start' => $todayStart,
				'end' => $todayEnd,
				'setting' => $todaySetting
			),
			'tomorrow' => array (
				'day_start' => strtotime ( '+1 day',$dayStart),
				'day_end' => strtotime ( '+1 day', $dayEnd),
				'start' => strtotime ( '+1 day', $todayStart ),
				'end' => strtotime ( '+1 day', $todayEnd ),
				'setting' => $tomorrowSetting,
			),
			'afterTomorrow' => array (
				'day_start' => strtotime ( '+2 day', $dayStart),
				'day_end' => strtotime ( '+2 day', $dayEnd),
				'start' => strtotime ( '+2 day', $todayStart ),
				'end' => strtotime ( '+2 day', $todayEnd ),
				'setting' => $afterTomorrowSetting
			),
			'config_start' => $todayStart,
			'config_end' => $todayEnd
		);
	
		$OrderModel = D('Order');
		$orderTimes = array();
		$orders= $OrderModel->getBeauticianOrderTimes($id, $todayStart);
		if ($orders) {
			foreach ($orders as $key => $order) {
				$orderTimes [$order ['order_time']] = $order ['order_time'] + $order ['service_time'] * 60;
			}
		}
		
		$this->ajaxReturn (array('status' => 1, 'orderTimes' => $orderTimes, 'data' => array('time' => $data)));
	}
	
	/**
	 * 会员登录
	 */
	public function login() {
		if (IS_POST) {
			$BeauticianModel = D ( 'Beautician' );
			$mobile = I ( 'post.mobile' );
			$password = I ( 'post.password' );
			
			$where ['mobile'] = array (
				'eq',$mobile
			);
			$info = $BeauticianModel->where ( $where )->find ();
			if ($info) {
				$hash = checkPassword ($password, $info ['password']);
				if ($hash) {
					$RememberModel = M('beautician_remember_login');
					$created = time();
					$remember = md5($info ['id'] .'-'. $info ['password'].$created);
					$record = array(
						'hash' => $remember,
						'beautician_id' => $info ['id'],
						'created' => $created
					);
					$RememberModel->add($record);
					setcookie('hash', $remember, $created + 7 * 24 * 3600);
					
					$_SESSION ['beautician'] = serialize($info);
					
					$this->ajaxReturn(array('status' => 1, 'redirect' => U ( '/Beautician/beauticianOrder' ) ));
				} else {
					$this->ajaxReturn(array('status' => 0, 'message' => '手机或密码错误' ));
				}
			} else {
				$this->ajaxReturn ( array('status' => 0, 'message' => '登录失败'));
			}
		} else {
			$show = I('get.show');
			
			$this->assign('show', $show);
			$this->display ();
		}
	}
	
	/**
	 * 美容师评论列表
	 */
	public function myComment() {
		$id = getBeauticianId();
	
		$OrderCommentModel = D('OrderComment');
		
		$total = $OrderCommentModel->totalBeauticianComment($id);
		$page = new Page($total, self::MAX_LOAD_LIMIT);
		
		$comments = $OrderCommentModel->getBeauticianComments($id, $page->firstRow, $page->listRows);
		if ($comments) {
			$UserModel = D('User');
			foreach ($comments as &$comment) {
				$comment ['user_info'] = $UserModel->getUserById($comment ['uid']);
				$comment ['start'] = floor($comment ['avg_score']);
				$commentPhoto = $OrderCommentModel->getCommentPhoto($comment ['id']);
				$comment ['photos'] = $commentPhoto;
				$reply = $OrderCommentModel->where(array('parentid' => $comment ['id']))->find();
				if ($reply) {
					$replyPhoto = $OrderCommentModel->getCommentPhoto($reply ['id']);
					$reply ['photos'] = $replyPhoto;
					$reply ['beautician'] = getBeautician();
						
					$comment ['reply'] = $reply;
				}
			}
		}
		
		$pageNumber = I('get.p')?I('get.p'):1;
		$hasMore = false;
		if ($total > $pageNumber * self::MAX_LOAD_LIMIT) {
			$hasMore = true;
		
			$nextPage = U('/Beautician/myComment/id/'.$id.'/p/'. ($pageNumber + 1));
			$this->assign('nextPage', $nextPage);
		}
		
		if (IS_AJAX) {
			$this->ajaxReturn(array('status' => 1, 'data' => $comments, 'hasMore' => $hasMore, 'nextPage' => $hasMore?$nextPage:false));
		} else {
			$this->assign('hasMore', $hasMore);
			$this->assign('comments', $comments);
			$this->display();
		}
	}
	
	public function reflushComments() {
		 $this->ajaxReturn(array('status' => 0));
	}
	
	/**
	 * 重置密码
	 */
	public function repeat() {
		if (IS_POST) {
			$mobile = I ( 'post.mobile' );
			$password = I ( 'post.password' );
			
			$BeauticianModel = D('Beautician');
			
			$user = $BeauticianModel->findByMobile($mobile);
			if (!$user) {
				$this->ajaxReturn(array('status' => 0, 'message' => '该手机未绑定，美容师未绑定'));
			}
			
			$captcha = randomPhoneCode(6);
			$_SESSION ['captchaTwo'] = $captcha;
			$LchiObj = new LanzSMSDirectSendSMS();
			$result = $LchiObj->send($mobile,$captcha.'(您的美滴滴身份验证码)，有效期为10分钟。如非本人操作，请忽略此短信');
			$params = array(
				'mobile' => $mobile,
				'type' => 'verification',
				'status' => $result?1:0
			);
			\Think\hook::listen('message_record', $params);
			if ($result) {
				$_SESSION ['mobile'] = $mobile;
				$_SESSION ['password'] = $password;
				
				$this->ajaxReturn(array('status' => 1, 'redirect' => U('confirmResetPassword')));
			} else {
				$this->ajaxReturn(array('status' => 0, 'message' => '重置密码失败，请稍候重试'));
			}
		} else {
			$this->display ();
		}
	}
	
	/**
	 * 提交回复
	 */
	public function reply() {
		$orderId = I('post.post_id');
		$OrderModel = D('Order');
		$orderInfo = $OrderModel->getOrderInfo($orderId);
		if ($orderInfo ['status'] != 4) {
			$this->nodata('服务未使用，不能进行评论');
		}
			
		$toUid = I ('post.to_uid');
		$OrderCommentModel = D('OrderComment');
		$comment = $OrderCommentModel->getCommentByOrderIdAndUid($orderId, $toUid);
		if (!$comment) {
			$this->nodata('用户未评论，不能回复');
		}
			
		$OrderCommentModel = D('OrderComment');
		$result = $OrderCommentModel->addComment();
		if (!$result) {
			$this->nodata($OrderCommentModel->getError());
		} else {
			redirect(U('Comments/replyComment/id/'.I('post.post_id')));
		}
	}
	
	/**
	 * 订单使用
	 */
	public function startUse() {
		$orderId = I('get.id');
	
		if (isset($_SESSION ['current_service'])) {
			$this->ajaxReturn(array('status' => 0, 'message' => '不能同时服务多个客户'));
// 			$currentService = unserialize($_SESSION ['current_service']);
// 			if ($currentService ['end_service_time'] > time()) {
// 				$this->ajaxReturn(array('status' => 0, 'message' => '不能同时服务多个客户'));
// 			}
		}
		
		$OrderModel = D('Order');
		$orderInfo = $OrderModel->getOrderInfo($orderId);
		
		$beauticianId = getBeauticianId();
		if ($orderInfo ['beautician_id'] != $beauticianId) {
			$this->ajaxReturn(array('status' => 0, 'message' => '服务开启失败'));
		}
	
		switch ($orderInfo ['status']) {
			case 0:
				$this->ajaxReturn(array('status' => 0, 'message' => '订单已删除'));
				break;
			case 2:
				$this->ajaxReturn(array('status' => 0, 'message' => '订单未支付'));
				break;
			case 4:
				$this->ajaxReturn(array('status' => 0, 'message' => '订单已使用'));
				break;
			case 5:
				$this->ajaxReturn(array('status' => 0, 'message' => '订单已取消'));
				break;
		}
	
		$result = $OrderModel->where(array('id' => $orderId))->save(array('status' => 3, 'use_time' => time()));
		$seconds = $orderInfo ['service_time'] * 60;
		if ($result) {
			$complete = time() > ($orderInfo ['order_time'] + $seconds)?true:false;
			if (!$complete) {
				$_SESSION ['current_service'] = serialize(array(
					'start_service_time' => time(),
					'end_service_time' => time() + $seconds,
					'order_id' => $orderInfo ['id']
				));
			}
	
			$OrderModel->clearCache($orderId);
			$data =array(
				'status' => 1, 
				'time' => $seconds * 1000,
				'complete' => $complete
			);
			if ($complete) {
				$data ['order'] = $orderInfo;
			}
			
			$this->ajaxReturn($data);
		} else {
			$this->ajaxReturn(array('status' => 0, 'message' => '开启服务失败！'));
		}
	}
	
	/**
	 * 订单信息查看
	 */
	public function showOrder() {
		$id = I ('get.id');
	
		$OrderModel = D('Order');
		$orderInfo = $OrderModel->getOrderInfo($id);
	
		$UserModel = D('User');
		$userInfo = $UserModel->getUserById($orderInfo ['user_id']);
	
		$ServiceModel = D('ServiceItem');
		$service = $ServiceModel->getServiceInfo($orderInfo ['service_id']);
	
		$BeautyParlor = D('BeautyParlor');
		$orderInfo ['beauty'] = $BeautyParlor->getBeautyInfo($orderInfo ['beauty_id']);
		
		if ($orderInfo ['status'] == 3 &&
			(($orderInfo ['order_time'] + $orderInfo ['service_time'] * 60) < $orderInfo ['use_time']
				|| ($orderInfo ['use_time'] + $orderInfo ['service_time'] * 60) < time())) {
			$orderInfo ['check_complete'] = true;
		} else if ($orderInfo ['status'] == 3){
			$timer = $orderInfo ['use_time'] + $orderInfo ['service_time']* 60 - time();
			$this->assign('timer', $timer * 1000);
		}
		
		$this->assign('service', $service);
		$this->assign('order', $orderInfo);
		$this->assign('user', $userInfo);
		$this->display();
	}
	
	public function sendCode() {
		$mobile = $_SESSION ['mobile'];
		$captcha = randomPhoneCode(6);
		$_SESSION ['captchaTwo'] = $captcha;
		$LchiObj = new LanzSMSDirectSendSMS();
		$result = $LchiObj->send($mobile,$captcha .'(您的美滴滴身份验证码)，有效期为10分钟。如非本人操作，请忽略此短信');
		
		$params = array(
			'mobile' => $mobile,
			'type' => 'verification',
			'status' => $result?1:0
		);
		\Think\hook::listen('message_record', $params);
		
		if (!$result) {
			$this->ajaxReturn(array('status' => 0, 'message' => '发送验证码失败'));
		} else {
			$this->ajaxReturn(array('status' => 1));
		}
	}
	
	/**
	 * 手机短信验证
	 */
	public function confirmResetPassword() {
		$mobile = $_SESSION ['mobile'];		
		
		if (IS_POST) {
			$BeauticianModel = D ( 'Beautician' );
			$verify = I ( 'post.verify' );
			$captcha = $_SESSION ['captchaTwo'];
			// 接收随机数
			if ($verify == $captcha) {
				$password = $_SESSION ['password'];
				$passwordTwo = hashPassword( $password );
				$data ['password'] = $passwordTwo;
				$result = $BeauticianModel->where ( "mobile='$mobile'" )->save( $data );
				if (!$result) {
					$this->ajaxReturn(array('status' => 0, 'message' => '验证失败'));
				} else {
					$this->ajaxReturn(array('status' => 1, 'redirect' => U('/Beautician/login/show/1')));
				}
			} else {
				$this->ajaxReturn(array('status' => 0, 'message' => '验证码错误'));
			}
		} else {
			$this->assign ( 'mobile', $mobile );
			$this->display ('sendCode');
		}
	}
	
	/**
	 * 服务商圈
	 */
	public function service() {
		$id = getBeauticianId();		
		// 查询美容师
		$BeauticianModel = D ( 'Beautician' );
		
		$beautician = getBeautician();
		
		$longitude = $beautician ['longitude'];
		$latitude = $beautician ['latitude'];
		
		// 查询美容院
		$beautyModel = M ( 'beauty_parlor' );
		$empList = M('beauty_parlor_employe')->field(array('bp.id'))
			->join('emp left join mdd_beauty_parlor as bp on emp.bp_id=bp.id')
			->where(array(
				'bp.province' => $beautician ['province'],
				'bp.city' => $beautician ['city'],
				'emp.beautician_id' => $id,
				'emp.status'	=> 1
			))->select ();
			
		if ($empList) {
			$empList = array_map(function ($var) {return $var['id'];}, $empList);
		}
			
		$beautyList = $beautyModel->where(array('province' => $beautician ['province'],
			'city' => $beautician ['city']
		))->select();
		
		$start = array('latitude' => $beautician ['latitude'],
			'longitude' => $beautician ['longitude']
		);
		
		foreach ( $beautyList as $k => &$v ) {
			if (in_array($v ['id'], $empList)) {
				$v ['selected'] = true;
			}
			$end = array('latitude' => $v ['latitude'],
				'longitude' => $v ['longitude']
			);
			
			$d = getDistance($start, $end);
			$v ['mathDis'] = $d;
			if ($d < 1) {
				$v ['jsonStr'] = round($d * 1000).'米';
			} else {
				$v ['jsonStr'] = round($d, 1).'公里';
			}
		}
		
		$beautyList = multi_array_sort($beautyList, 'mathDis');
		$this->assign ( 'beautician', $beautician );
		$this->assign ( 'beautyList', $beautyList );
		$this->display ();
	}
	
	public function selectBeauty() {
		$beautyId = I ('get.beauty_id');
		
		$beauticianId = getBeauticianId();
		
		$EmployeModel = D('BeautyParlorEmploye');
		$where = array('bp_id' => $beautyId, 'beautician_id' => $beauticianId);
		
		$empRecord = $EmployeModel->where($where)->find();
		if ($empRecord) {
			if ($empRecord ['status'] == 1) {
				$data ['status'] = 0;
			} else {
				$data ['status'] = 1;
			}
			$result = $EmployeModel->where($where)->save($data);
		} else {
			$data = $where;
			$data ['status'] = 1;
			$data ['created'] = time();
			$result = $EmployeModel->add($data);
		}
		
		if ($result) {
			$this->ajaxReturn(array('status' => 1));
		} else {
			$this->ajaxReturn(array('status' => 0));
		}
	}
	
	/**
	 * 日程管理
	 */
	public function scheduleManage() {
		$schedule = D('Schedule');
		if (IS_POST) {
			//点击上班		
			$setting = I('post.setting');
			$beauticianId = getBeauticianId();
			
			$currentDate = strtotime(date('Y-m-d', time()));
			
			$ScheduleModel = M('schedule');
			
			$where = array('CurrentDate' => $currentDate, 'uid' => $beauticianId);
			$todayHasSetting = $ScheduleModel->where($where)->find();
			if ($todayHasSetting) {
				$data = array('workTime' => serialize($setting));
				$result = $ScheduleModel->where($where)->save($data);
			} else {
				$data = array('workTime' => serialize($setting), 'CurrentDate' => $currentDate, 'uid' => $beauticianId);
				$result = $ScheduleModel->add($data);
			}
			
			if ($result) {
				$this->ajaxReturn(array('status' => 1));
			} else {
				$this->ajaxReturn(array('status' => 0));
			}
		}else {			
			//查询上班时间
			$uid=getBeauticianId();
			$this->assign('today', time());
			$this->display();				
		}	
	}
}